package com.company.netty;

import java.nio.charset.StandardCharsets;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class MessageDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        // 确保有足够数据: 类型(4) + 长度(4) + 内容
        if (in.readableBytes() < 8) return;
        
        in.markReaderIndex();
        int type = in.readInt();
        int length = in.readInt();
        
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        }
        
        byte[] content = new byte[length];
        in.readBytes(content);
        out.add(new CustomMessage(type, new String(content, StandardCharsets.UTF_8)));
    }
}
